package com.example.demo.service.impl;

import com.example.demo.config.RedisCache;
import com.example.demo.model.User;
import com.example.demo.service.LoginService;
import com.example.demo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisTemplate;

    @Override
    public ResponseEntity login(User user) {
        //web服务器首先会执行 JwtAuthenticationTokenFilter

        // 认证的时候需要Authentication对象，所以需要一个Authentication的实现类，这里选择了UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getName(),user.getPassword());

        // AuthenticationManager authenticate方法进行认证。在SecurityConfig配置类中，将AuthenticationManager注入到容器中。
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证通过，authenticate里将包含principal属性，该属性的值就是LoginUser，
        // 如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        // 如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        User loginUser = (User) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginUser.getId().toString());
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);

        // 把完整的用户信息存入redis，userid作为key
        redisTemplate.setCacheObject("login:" + loginUser.getId().toString(), loginUser);

        return new ResponseEntity(loginUser, HttpStatus.valueOf(HttpStatus.OK.value()));
    }

}
